import 'package:flutter_admin/pages/common/cry/cry.dart';
import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/cry_buttons.dart';
import 'package:flutter_admin/pages/common/cry/cry_dialog.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select_date.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/api/odoo/product_equhisdata_odoo_api.dart';
import 'package:flutter_admin/constants/enum.dart';
import 'package:flutter_admin/generated/l10n.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/models/odoo/product_equhisdata.dart';
import 'package:flutter_admin/pages/common/date_time_select.dart';
import 'package:flutter_admin/pages/odoo/product_equhisdata/product_equhisdata_chart.dart';
import 'package:flutter_admin/pages/odoo/product_equhisdata/product_equhisdata_dialog.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';
import 'package:flutter_admin/utils/utils.dart';
import 'package:intl/intl.dart';

class ProductEquhisdataList extends StatefulWidget {
  ProductEquhisdataList({Key? key}) : super(key: key);

  @override
  _ProductEquhisdataListState createState() => _ProductEquhisdataListState();
}

class _ProductEquhisdataListState extends State<ProductEquhisdataList> {
  final GlobalKey<CryDataTableState> tableKey = GlobalKey<CryDataTableState>();
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  PageModel page =
      PageModel(orders: [OrderItemModel(column: 'histime', asc: true)]);
  ProductEquhisdata productEquhisdata = ProductEquhisdata();
  List<ProductEquhisdata> selectedList = [];
  //设备名称
  List<SelectOptionVO> devList = [];
  //参数名称
  List<SelectOptionVO> unitnameList = [];
  //采集时间
  List<SelectOptionVO> histimeList = [];

  DateFormat format = DateFormat('yyyy-MM-dd HH:mm:ss');

  @override
  void initState() {
    super.initState();
    productEquhisdata.histimeStart = Utils.getDate()+" 00:00:00";
    productEquhisdata.histimeEnd = Utils.getDate()+" 23:59:59";
    WidgetsBinding.instance!.addPostFrameCallback((c) {
      _query();
      _loadSelectVO();
    });
  }

  _loadSelectVO() async {
    //设备名称
    devList = await DynamicDataApi.getModelSelect(
        model: 'base.productionstation',
        tag: 'epu_id',
        name: 'stationname',
        key: 'isproduction',
        val: '1');
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          DateTimeSelect(
            context,
            width: 230,
            label: '采集开始日期',
            value: productEquhisdata.histimeStart,
            lastDate: productEquhisdata.histimeEnd != '' &&
                    productEquhisdata.histimeEnd != null
                ? format.parse(productEquhisdata.histimeEnd!)
                : null,
            onDateChange: (v) {
              formKey.currentState?.save();
              productEquhisdata.histimeStart = v;
              setState(() {});
            },
            onSaved: (v) {
              productEquhisdata.histimeStart = v;
            },
          ),
          DateTimeSelect(
            context,
            width: 230,
            label: '采集结束时间',
            value: productEquhisdata.histimeEnd,
            firstDate: productEquhisdata.histimeStart != '' &&
                    productEquhisdata.histimeStart != null
                ? format.parse(productEquhisdata.histimeStart!)
                : null,
            onDateChange: (v) {
              formKey.currentState?.save();
              productEquhisdata.histimeEnd = v;
              setState(() {});
            },
            onSaved: (v) {
              productEquhisdata.histimeEnd = v;
            },
          ),
          CrySelect(
            width: 350,
            label: '设备名称',
            dataList: devList,
            value: productEquhisdata.devid,
            onChange: (v) async {
              if (productEquhisdata.devid != v) {
                formKey.currentState!.save();
                productEquhisdata.devid = v;
                productEquhisdata.unitname = null;
                try {
                  unitnameList = await DynamicDataApi.getModelSelect(
                      model: "product.equparameter",
                      tag: "unitname",
                      name: "unitname",
                      key: 'devid',
                      val: v,
                      active: false);
                } catch (e) {
                  unitnameList = [];
                }
                setState(() {});
              }
            },
            onSaved: (v) => {productEquhisdata.devid = v},
          ),
          CrySelect(
            width: 280,
            label: '参数名称',
            dataList: unitnameList,
            value: productEquhisdata.unitname,
            onSaved: (v) => {productEquhisdata.unitname = v},
          ),
        ],
      ),
    );

    CryDataTable table = CryDataTable(
      key: tableKey,
      title: "数据列表",
      showCheckboxColumn: false,
      actions: !isDisplayDesktop(context)
          ? [
              _operationList(),
            ]
          : [],
      onPageChanged: (firstRowIndex) {
        page.current = (firstRowIndex ~/ page.size + 1);
        _loadData();
      },
      onRowsPerPageChanged: (int size) {
        page.size = size;
        page.current = 1;
        _loadData();
      },
      onSelectChanged: (Map selected) {
        this.setState(() {});
      },
      columns: [
        //isDisplayDesktop(context)?DataColumn(
        //  label: Text(S.of(context).operating),
        //):DataColumn(label: Container()),
        DataColumn(
          label: Text('设备编码'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('设备名称'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),

        DataColumn(
          label: Text('参数类型名称'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        // DataColumn(
        //   label: Text('参数编号'),
        //   //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        // ),
        DataColumn(
          label: Text('参数名称'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('参数单位'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('采集参数值'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('采集时间'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),

        DataColumn(
          label: Text('创建时间'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
      ],
      getCells: (m) {
        ProductEquhisdata productEquhisdata = ProductEquhisdata.fromMap(m);
        return [
          //isDisplayDesktop(context)?DataCell(
          //  CryButtonBar(
          //    children: [
          //      CryButton(
          //          iconData: Icons.edit,
          //          tip: S.of(context).modify,
          //          onPressed: () => _edit(productEquhisdata)),
          //    ],
          //  ),
          // ):DataCell(Container()),
          DataCell(Text(productEquhisdata.equcode ?? '--')),
          DataCell(Text(productEquhisdata.equname ?? '--')),
          DataCell(Text(productEquhisdata.datatypename ?? '--')),
          // DataCell(Text(productEquhisdata.dataname ?? '--')),
          DataCell(Text(productEquhisdata.unitname ?? '--')),
          DataCell(Text(productEquhisdata.unitcode ?? '--')),
          DataCell(Text(productEquhisdata.timevalue ?? '--')),
          DataCell(Text(productEquhisdata.histime ?? '--')),
          DataCell(Text(productEquhisdata.createDate!)),
        ];
      },
    );
    _getSelectList();
    CryButtonBar buttonBar = CryButtonBar(
      children: <Widget>[
        CryButtons.query(context, () => _query()),
        CryButtons.reset(context, () => _reset()),
        CryButton(
          label: "导出",
          onPressed: () => _generateExcel(),
          iconData: Icons.import_export_outlined,
        ),
        CryButton(
          label: "趋势图",
          onPressed: () => _openChart(),
          iconData: Icons.import_export_outlined,
        )
      ],
    );
    var result = Scaffold(
      key: scaffoldStateKey,
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(height: 10),
          isDisplayDesktop(context) ? form : Container(),
          isDisplayDesktop(context) ? buttonBar : Container(),
          Expanded(child: SingleChildScrollView(child: table)),
        ],
      ),
    );
    return result;
  }

  Future<dynamic> findAll() async {
    formKey.currentState?.save();
    List<ProductEquhisdata> resultList = [];
    ResponseBodyApi responseBodyApi =
        await ProductEquhisdataOdooApi.findAll(data: {
      "domainList": productEquhisdata.toDomainList(),
    });
    if (responseBodyApi.success!) {
      resultList = responseBodyApi.data
              .map<ProductEquhisdata>((e) => ProductEquhisdata.fromMap(e))
              .toList() ??
          [];
    }
    return resultList;
  }

  _generateExcel() async {
    List<ProductEquhisdata> selectedList = await findAll();
    if (selectedList == null) {
      return;
    }
    List<Map> map = [
      {
        'name': 'equcode',
        'label': '设备编码',
        'columnWidth': 24.0,
      },
      {
        'name': 'equname',
        'label': '设备名称',
        'columnWidth': 20.0,
      },
      {
        'name': 'datatypename',
        'label': '参数类型名称',
        'columnWidth': 18.0,
      },
      {
        'name': 'dataname',
        'label': '参数编号',
        'columnWidth': 40.0,
      },
      {
        'name': 'unitname',
        'label': '参数名称',
        'columnWidth': 12.0,
      },
      {
        'name': 'unitcode',
        'label': '参数单位',
        'columnWidth': 12.0,
      },
      {
        'name': 'timevalue',
        'label': '采集参数值',
        'columnWidth': 14.0,
      },
      {
        'name': 'histime',
        'label': '采集时间',
        'columnWidth': 20.0,
      },
      {
        'name': 'createDate',
        'label': '创建时间',
        'columnWidth': 20.0,
      },
    ];
    Utils.generateExcel(
        fileName: "设备停机数据查询", configure: map, data: selectedList);
  }

  _openChart() {
    Utils.fullscreenDialog(ProductEquhisdataChart());
  }

  _reset() {
    productEquhisdata = ProductEquhisdata();
    productEquhisdata.histimeStart = Utils.getDate()+" 00:00:00";
    productEquhisdata.histimeEnd = Utils.getDate()+" 23:59:59";
    unitnameList = [];
    formKey.currentState!.reset();
    _loadData();
  }

  _query() {
    formKey.currentState?.save();
    tableKey.currentState?.pageTo(0);
    _loadData();
  }

  _loadData() async {
    ResponseBodyApi responseBodyApi = await ProductEquhisdataOdooApi.page(
        data: {"page": page, "domainList": productEquhisdata.toDomainList()});
    if (responseBodyApi.success!) {
      page = responseBodyApi.data != null ? responseBodyApi.data : PageModel();
      tableKey.currentState!.loadData(page);
      _getSelectList();
    }
  }

  // _sort(column, {ascending}) {
  //   page.orders[0].column = column;
  //   page.orders[0].asc = ascending ?? !page.orders[0].asc!;
  //   _query();
  // }

  _search() {
    return showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: ProductEquhisdataDialog(),
      ),
    ).then((v) {
      if (v != null) {
        productEquhisdata = v;
        _query();
      }
    });
  }

  _getSelectList() {
    selectedList = tableKey.currentState
            ?.getSelectedList(page)
            .map<ProductEquhisdata>((e) => ProductEquhisdata.fromMap(e))
            .toList() ??
        [];
    setState(() {});
  }

  _operationList() {
    return PopupMenuButton(
      onSelected: (dynamic v) {
        if (v == OperationType.query) {
          _search();
        }
      },
      itemBuilder: (context) => <PopupMenuEntry<OperationType>>[
        PopupMenuItem<OperationType>(
          value: OperationType.query,
          child: ListTile(
            leading: const Icon(Icons.search),
            title: Text('查询'),
          ),
        ),
      ],
    );
  }
}
